package com.htudata.common.conf;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = {"com.htudata.*.*.mapper"}, sqlSessionFactoryRef = "master1SqlSessionFactory")
public class Master1DataSourceConfig {

  @Value("${mapper.hieyes}")
  private String mapper_locations_hieyes;

  @Bean(name = {"master1DataSource"})
  @Primary
  @ConfigurationProperties(prefix = "spring.marster1.datasource")
  public DataSource masterDataSource() {
    return DataSourceBuilder.create().build();
  }
  
  @Bean(name = {"master1TransactionManager"})
  @Primary
  public DataSourceTransactionManager masterTransactionManager(@Qualifier("master1DataSource") DataSource masterDataSource) {
    return new DataSourceTransactionManager(masterDataSource);
  }
  
  @Bean(name = {"master1SqlSessionFactory"})
  @Primary
  public SqlSessionFactory masterSqlSessionFactory(@Qualifier("master1DataSource") DataSource masterDataSource) throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(masterDataSource);
    sessionFactory.setMapperLocations((new PathMatchingResourcePatternResolver())
        .getResources(mapper_locations_hieyes));
    return sessionFactory.getObject();
  }
}
